/**
 * @param {number[][]} grid
 * @return {number}
 */
var minPathSum = function (grid) {
  //定义一个变量：接收二维数组的行和列
  let m = grid.length
  let n = grid[0].length

  //定义一个状态数组
  const dp = Array.from({ length: m }, () => new Array(n).fill(0))
  //初始化
  dp[0][0] = grid[0][0]
  for (let i = 1; i < m; i++) {
    dp[i][0] = dp[i - 1][0] + grid[i][0]
  }
  for (let i = 1; i < n; i++) {
    dp[0][i] = dp[0][i - 1] + grid[0][i]
  }
  //求非第一行、第一列的状态
  for (let i = 1; i < m; i++) {
    for (let j = 1; j < n; j++) {
      dp[i][j] = grid[i][j] + Math.min(dp[i - 1][j], dp[i][j - 1])
    }
  }
  //返回状态数组
  return dp[m - 1][n - 1]
};
console.log(minPathSum([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))